<template>
  <el-aside
    class="search-result-aside border-l border-[var(--el-border-color)] bg-[var(--el-bg-color)]"
    width="360px"
  >
    <div
      class="search-result-header flex items-center justify-between p-15px border-b border-[var(--el-border-color)]"
    >
      <div class="font-bold">引用来源（{{ parsedSearchResults.length }}）</div>
      <el-button link @click="onClose">
        <el-icon><Close /></el-icon>
      </el-button>
    </div>
    <div class="search-result-content overflow-y-auto h-[calc(100%-60px)]">
      <div
        v-for="(result, index) in parsedSearchResults"
        :key="index"
        class="search-result-item p-15px border-b border-[var(--el-border-color)] hover:bg-[var(--el-fill-color-lighter)] cursor-pointer"
        @click="openResult(result.url)"
      >
        <div class="result-header flex flex-col items-start mb-8px">
          <div class="site-info flex items-center mb-8px text-12px line-height-18px">
            <span class="mr-10px">{{ index + 1 }}.</span>
            <img
              v-if="result.logo_url"
              :src="result.logo_url"
              :alt="result.site_name"
              class="site-logo w-16px h-16px rounded-full object-contain mr-5px"
              @error="handleLogoError(index)"
            />
            <span class="site-name">{{ result.site_name }}</span>
          </div>
          <div
            class="result-title font-medium text-14px text-[var(--el-text-color-primary)] text-overflow-2"
          >
            {{ result.title }}
          </div>
        </div>
        <div
          class="result-summary text-13px text-[var(--el-text-color-secondary)] text-overflow-3 mb-8px"
        >
          {{ result.summary }}
        </div>
        <div class="result-meta flex justify-between text-12px text-[var(--el-color-info)]">
          <span class="publish-time">{{ result.publish_time }}</span>
        </div>
      </div>
    </div>
  </el-aside>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, computed } from 'vue'
import { Close } from '@element-plus/icons-vue'
import { SearchReference } from '@/api/ai/chat/message'

// 定义搜索结果的联合类型
type SearchResults = SearchReference[] | string

const props = defineProps<{
  searchResults: SearchResults
}>()

const emit = defineEmits<{
  (e: 'close'): void
}>()

// 解析搜索结果数据
const parsedSearchResults = computed<SearchReference[]>(() => {
  if (typeof props.searchResults === 'string') {
    try {
      // 尝试解析JSON字符串
      const parsed = JSON.parse(props.searchResults)
      // 验证解析结果是否为SearchReference[]类型
      if (Array.isArray(parsed) && parsed.every((item) => 'title' in item && 'url' in item)) {
        return parsed
      }
      console.error('Invalid searchResults format: parsed data is not of type SearchReference[]')
      return []
    } catch (e) {
      console.error('Failed to parse searchResults as JSON:', e)
      return []
    }
  }
  return props.searchResults || []
})

const onClose = () => {
  emit('close')
}

const openResult = (url: string) => {
  if (url) {
    window.open(url, '_blank')
  }
}

const handleLogoError = (index: number) => {
  // 当logo加载失败时的处理逻辑
  console.log(`Logo load failed for item at index: ${index}`)
}
</script>

<style scoped lang="scss">
.search-result-aside {
  display: flex;
  height: 100%;
  margin-left: 12px;
  border-radius: 16px;
  flex-direction: column;
}

.search-result-content {
  flex: 1;
  overflow-y: auto;
}

.line-clamp-2 {
  display: -webkit-box;
  overflow: hidden;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.line-clamp-3 {
  display: -webkit-box;
  overflow: hidden;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}
</style>
